package id.co.rho.scoring.cid.client.widgets;

import java.math.BigDecimal;
import java.util.Date;

import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.google.gwt.i18n.client.DateTimeFormat;

import gxt.visual.ui.client.implementations.VDateField;

public class DirtyAwareDateField extends VDateField implements DirtyAwareField {
	Listener changeListener = new Listener<FieldEvent>() {
	      public void handleEvent(FieldEvent be) {
	        onFieldChange(be);
	      }
	    };

	boolean dirtyPrevState = false;
	
	
	public DirtyAwareDateField() {
		super();
		addListener(Events.Change, changeListener);	
	}

	@Override
	public void resetDirtyness() {
		dirtyPrevState = false;
		UIHelper.removeDirtyMarker(this);
		onFieldChange(null);
	}
	
	private void onFieldChange(FieldEvent be) {
		boolean dirty = isDirty();
		if(dirty != dirtyPrevState) {
			dirtyPrevState = dirty;
			if(dirty) {
				UIHelper.applyDirtyMarker(this);
			}else {
				UIHelper.removeDirtyMarker(this);
			}
		}
	}
	
	public boolean isDirty(){
		if (disabled || !rendered) {
		      return false;
		    }
		return !isEqual(getValue(), originalValue);
	}
	
	private boolean isEqual(Date val1, Date val2) {
		if(val1==null){
			return val2==null;
		}else{
			if(val2==null){
				return false;
			}else{
				DateTimeFormat yearFormat = DateTimeFormat.getFormat("y");
				DateTimeFormat monthFormat = DateTimeFormat.getFormat("MM");
				DateTimeFormat dateFormat = DateTimeFormat.getFormat("dd");
				
				if(dateFormat.format(val1).equalsIgnoreCase(dateFormat.format(val2))){
					if(monthFormat.format(val1).equalsIgnoreCase(monthFormat.format(val2))){
						if(yearFormat.format(val1).equalsIgnoreCase(yearFormat.format(val2))){
							return true;
						}
					}
				}
				return false;
			}
		}
    }

}
